// 导出函数
import XlsxPopulate from 'xlsx-populate'
// 列名元素集
// eslint-disable-next-line standard/array-bracket-even-spacing
const COL_ABC = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' ]

export const excel = (excelName, callBack, execlData, param = '') => {
  return XlsxPopulate.fromBlankAsync()
    .then(workbook => {
      let sheet = workbook.sheet('Sheet1')
      callBack(sheet, excelName, execlData, param)
      workbook.outputAsync().then(function (blob) {
        if (window.navigator && window.navigator.msSaveOrOpenBlob) {
          // If IE, you must uses a different method.
          window.navigator.msSaveOrOpenBlob(blob, `${excelName}.xlsx`)
        } else {
          let url = window.URL.createObjectURL(blob)
          let a = document.createElement('a')
          document.body.appendChild(a)
          a.href = url
          a.download = `${excelName}.xlsx`
          a.click()
          window.URL.revokeObjectURL(url)
          document.body.removeChild(a)
        }
      })
    })
}

/**
 * 获取列名
 * @colIndex 列序号（从0开始）
 * @returns 列名
 */
export function getColName (colIndex) {
  if (colIndex < 0) {
    return ''
  }
  let colNames = []
  // 等于0 和 大于25 的 colIndex
  let isAdd1 = colIndex > 25 || colIndex < 1
  // 10进制转26进制
  let kArray = ckqy(colIndex + (isAdd1 ? 1 : 0), 26)
  for (let i = 0; i < kArray.length; i++) {
    colNames.push(COL_ABC[ kArray[i] - (isAdd1 ? 1 : 0) ] || '')
  }
  return colNames.join('')
}
/**
* 十进制的数化为k进制的数【返回数组的index=0位置是最高位】（取k取余法）
* @num 10进制数
* @k k
* @returns k进制数序列
 */
function ckqy (num, k) {
  let y = []
  while (num > 0) {
    let s = Math.floor(num / k)
    let _y = num % k
    if (s === 0) {
      y.push(num)
      num = 0
    } else {
      y.push(_y)
      num = s
    }
  }
  return y.reverse()
}
